package com.sxjh.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sxjh.entity.User;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * MP注入处理器
 * @author Lion Li
 * @date 2021/4/25
 */
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

	@Override
	public void insertFill(MetaObject metaObject) {
		//根据属性名字设置要填充的值
		if (metaObject.hasGetter("createdAt")) {
			if (metaObject.getValue("createdAt") == null) {
				this.setFieldValByName("createdAt", LocalDateTime.now(), metaObject);
			}
		}
		if (metaObject.hasGetter("createdBy")) {
			if (metaObject.getValue("createdBy") == null) {
				User user = AuthContent.getUser();
				if (user != null) this.setFieldValByName("createdBy", AuthContent.getUser().getId(), metaObject);
				else this.setFieldValByName("createdBy", 0, metaObject);
			}
		}
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		if (metaObject.hasGetter("updatedBy")) {
			if (metaObject.getValue("updatedBy") == null) {
				User user = AuthContent.getUser();
				if (user != null) this.setFieldValByName("updatedBy", AuthContent.getUser().getId(), metaObject);
				else this.setFieldValByName("updatedBy", 0, metaObject);
			}
		}
		if (metaObject.hasGetter("updatedAt")) {
			//if (metaObject.getValue("updatedAt") == null) {
				this.setFieldValByName("updatedAt", LocalDateTime.now(), metaObject);
			//}
		}
	}

}
